package com.self.hctransfer.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.self.hctransfer.core.WordExportController;

@Controller
@RequestMapping("/file")
public class FileController {
	
	@Value("${myvalue.filepath}")
	private String filePath;
	
	/**
	 * 返回首页
	 */
	@GetMapping("/")
	public String index() {
		return "index";
	}
	
	
	/**
	 * 保存文件
	 * todo
	 */
	
	@PostMapping("/upload")
	@ResponseBody
	public String springUpload(@RequestParam("fileName") MultipartFile[] files,HttpServletRequest request,Model model) throws IllegalStateException, IOException 		
	{
		/*
		 * for(MultipartFile f : files) { System.out.println(f.getOriginalFilename()); }
		 */
		String path = FileController.class.getResource("/").getPath()  + filePath;
		// 时间格式换
		//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		File folder = new File( path );
		if(!folder.exists()) folder.mkdir();
		String newFilePath = null;
		List<String> ls = new ArrayList<String>();
		for(int i=0 ; i < files.length; i++) {
			if(files[i].getSize() != 0) {
				System.out.println(files[i].getOriginalFilename());
				 newFilePath = path+ files[i].getOriginalFilename();
				files[i].transferTo(new File(newFilePath));
				ls.add(newFilePath);
			}
		}		
		model.addAttribute("list", ls);
		return newFilePath + "成功";
	}
	
	/**
	 * 下载文件
	 * todo
	 */

 
	@GetMapping("/down")
    public ResponseEntity<FileSystemResource> down() throws UnsupportedEncodingException{
		
		String realdocurl=FileController.class.getResource("/").getPath()  + filePath +"result.docx";
		
		try {
			WordExportController.create(FileController.class.getResource("/").getPath()  + filePath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        File file = new File(realdocurl);
        if (file == null){
        	System.out.println("123");
            return null;
        }
        
        String suffixType =realdocurl.substring(realdocurl.lastIndexOf("."));
        String newfilename ="对比结果"+suffixType;
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" +  URLEncoder.encode(newfilename, "UTF-8"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    
		
		
	}
	
}
